﻿using Abp.Application.Services;
using AbpVueDemo.Demo.FileMananger.Dto;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace AbpVueDemo.Demo.FileMananger
{
    /// <summary>
    /// 不需要增删改查  继承ApplicationService
    /// </summary>
    public class FileManagerService : ApplicationService
    {
        static string configPath = "";
        public FileManagerService(IConfiguration configuration)
        {
            if (string.IsNullOrEmpty(configPath))
            {
                configPath = configuration.GetSection("MyConfig")["FileUploadPath"];
            }
        }

        /// <summary>
        /// 
        /// 多文件上传
        /// </summary>
        /// <param name="fileList">多个文件</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<FileUpLoadResult>> FilesUpload(List<IFormFile> fileList)
        {
            List<FileUpLoadResult> fulList = new List<FileUpLoadResult>();
            if (fileList != null && fileList.Count > 0)
            {


                foreach (var iFormFile in fileList)
                {
                    FileUpLoadResult ful = new FileUpLoadResult();
                    //新的文件名
                    string fileName = Guid.NewGuid() + Path.GetExtension(iFormFile.FileName);
                    //新的文件路径
                    string urlPath = configPath + "/" + fileName;
                    //新的文件存储物理路径   FileTools.MapPath类似.NetFramwork 的Server.MapPath();
                    string upLoadPath = Environment.CurrentDirectory + "/wwwroot" + configPath;
                    ful.FileOldName = iFormFile.FileName;  //提取上传文件的温家明
                    ful.FileNewName = fileName;
                    ful.FileNewPath = urlPath;
                    ful.FileSize = iFormFile.Length;
                    ful.FileType = iFormFile.ContentType;
                    if (!Directory.Exists(upLoadPath))  //如果目录不存在
                    {
                        Directory.CreateDirectory(upLoadPath); //创建一个目录
                    }
                    try
                    {
                        using (var fs = new FileStream(upLoadPath + "/" + fileName, FileMode.Create))
                        {
                            await iFormFile.CopyToAsync(fs); //把上传文件复制到 fs 文件流中
                            fs.Flush();   //写入到硬盘中
                            ful.IsUpload = true;  //上传成功
                        }

                    }
                    catch (Exception ex)
                    {
                        ful.IsUpload = false;
                    }
                    fulList.Add(ful);

                }
                return fulList;

            }
            else
            {
                throw new Exception("没有上传文件");
            }
        }

    }
}
